﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using IrisGenerator.Common.Tools;

namespace IrisGenerator.Common.DatabaseModel
{
    public class ConstraintCollection:Collection<Constraint>
    {
        public ConstraintCollection GetConstraintFromConstraintTypeName(string ConstraintTypeName)
        {
            var result = from cons in this
                         where (cons.ConstraintType.Name.Equals(ConstraintTypeName))
                         select cons;
            return ConstraintCollection.FromIEnumarable(result);
        }

        public bool ConstraintTypeExists(string ConstraintTypeName)
        {
            var result = from cons in this
                         where (cons.ConstraintType.Name.Equals(ConstraintTypeName))
                         select cons;

            return (result.Count() > 0);
        }

        internal static ConstraintCollection FromIEnumarable(IEnumerable<Constraint> constraints)
        {
            ConstraintCollection returnValue = new ConstraintCollection();
            foreach (Constraint cons in constraints)
            {
                returnValue.Add(cons);
            }
            return returnValue;
        }

        public static ConstraintCollection GetTableConstraints(Table table)
        {
            if (table == null)
                return null;

            IrisGenerator.Common.DatabaseModel.DataAccess.Constraint dbo = null;
            try
            {
                dbo = new IrisGenerator.Common.DatabaseModel.DataAccess.Constraint();
                System.Data.DataSet ds = dbo.TableConstraints(table.TabId);
                ConstraintCollection col = new ConstraintCollection();
                if (GlobalTools.IsSafeDataSet(ds))
                {
                    for (int i = 0; (i < ds.Tables[0].Rows.Count); i = (i + 1))
                    {
                        Constraint obj = new Constraint();
                        obj.Fill(ds.Tables[0].Rows[i]);
                        if ((obj != null))
                        {
                            col.Add(obj);
                        }
                    }
                }
                return col;
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                if ((dbo != null))
                {
                    dbo.Dispose();
                }
            }
        }

        
    }
}
